import axios, { AxiosRequestConfig } from "axios";

import { BASE_URL } from "./config";
import { MyResponseType } from "../types";

const service = axios.create({
  baseURL: BASE_URL,
  // timeout: TIMEOUT,
});

// http request 拦截器
service.interceptors.request.use(
  (config) => {
    // 发送网络请求时, 在界面的中间位置显示Loading的组件,使用ant-design插件，这里不再赘述

    //请求公共参数携带的信息
    // config.headers.ak = localStorage.getItem('ak') || "";
    config.headers.sessionId = 15320748258726
    config.headers.userId = 10
    // config.headers["Content-Type"] = "application/x-www-form-urlencoded";

    return config;
  },
  (err) => {
    //...关闭加载loading的组件，显示消息提示弹窗
    return Promise.reject(err);
  }
);

// http response 拦截器
service.interceptors.response.use(
  (res) => {
    const { code } = res.data;
    switch (code) {
      case 9999:
        console.log("登录状态失效，请重新登录");
        break;
      case 9001:
        console.log("服务端错误");
        break;
      case 8001:
        console.log("用户业务错误");
        break;
      case 8002:
        console.log("医生业务错误");
        break;
      case 8003:
        console.log("公共业务错误");
        break;
    }
    return res;
  },
  (err) => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          console.log("请求错误");
          break;
        case 401:
          console.log("未授权访问");
          break;
        case 404:
          console.log("资源找不到");
          break;
        default:
          console.log("其他错误信息");
      }
    }
    return Promise.reject(err);
  }
);

const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<MyResponseType<T>> => {
  try {
    const resp = await service.request<MyResponseType<T>>(config);
    return resp.data;
  } catch (err: any) {
    const message = err.message || "请求失败";
    console.error(message); // 失败消息提示
    return {
      code: -1,
      message,
      data: null as any,
    };
  }
};

export default request;
